package team.bailan.common.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import team.bailan.common.config.ReturnResponse;
import team.bailan.common.enums.ReturnStatus;
import team.bailan.common.util.JwtUtil;
import team.bailan.common.util.NeedVerify;
import team.bailan.entity.domain.User;
import team.bailan.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(NeedVerify.class)) {
            DecodedJWT tokenInfo = JwtUtil.getTokenInfo();
            if (token != null && tokenInfo != null) {
                return true;
            }
//            handleNotAuthorized(request, response, handler);
            result(response, ReturnResponse.packageObject("token_error", ReturnStatus.AUTHORIZATION_FAILED));
            return false;
        }
        return true;
    }
    protected void handleNotAuthorized(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws ServletException, IOException {
        // 403表示资源不可用。服务器理解用户的请求，但是拒绝处理它，通常是由于权限的问题
//        response.setHeader("message", "token验证失败");
        response.sendError(403);
    }

    private void result(HttpServletResponse response, ReturnResponse<String> result){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(200);
        try (PrintWriter out = response.getWriter()) {
            out.append(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
